package com.xdja.netty.learn.arpackage;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.ReferenceCountUtil;

import java.util.List;

/**
 * description
 *
 * @author zk
 * @since 2018/7/25
 */
public class ZServer {
    public static void main(String[] args) throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        ChannelFuture channelFuture = serverBootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline()
//                                .addLast(new TailFixedLengthFrameDecoder(6))
                                .addLast(new ByteToMessageDecoder() {
                                    @Override
                                    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
                                        if (in.readableBytes() > 4) {
                                            out.add(in.readInt());
                                        } else if (in.readableBytes() == 4){
                                            out.add(in.readInt());
                                        }
                                    }

                                    @Override
                                    protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
                                        if(in.readableBytes() != 0){
                                            out.add(in.readInt());
                                        }
                                        ReferenceCountUtil.release(in);
                                    }
                                })
                        .addLast(new MessageToMessageDecoder<Integer>() {
                            @Override
                            protected void decode(ChannelHandlerContext ctx, Integer msg, List<Object> out) throws Exception {
                                System.out.println(msg);
                            }
                        });
                    }
                }).bind(8989).sync();
        channelFuture.channel().closeFuture().sync();
    }
}
